package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.AuthorMapper;
import com.heima.article.service.ApArticleService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.dtos.ArticleInfoDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.constants.ArticleConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;


@Service
@Transactional
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    //注入 文章 接口
    @Autowired
    private  ApArticleMapper apArticleMapper;

    @Autowired
    AuthorMapper authorMapper;

    @Autowired
    ApArticleConfigMapper apArticleConfigMapper;
    @Autowired
    ApArticleContentMapper apArticleContentMapper;

    /**
     * 保存app文章
     *
     * @param articleDto
     * @return
     */
    @Override
    public ResponseResult saveArticle(ArticleDto articleDto) {
        // 参数检查
        if (articleDto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //1 保存article 文章数据， 设置作者id
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(articleDto, apArticle);
        // 设置作者的id
        ApAuthor apAuthor = authorMapper.selectOne(Wrappers.<ApAuthor>lambdaQuery()
                .eq(ApAuthor::getName, apArticle.getAuthorName()));
        if (apAuthor == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        apArticle.setAuthorId(apAuthor.getId().longValue());

        if (articleDto.getId() == null) {  // 保存

            // 普通文章
            apArticle.setComment(0);
            apArticle.setViews(0);
            apArticle.setCollection(0);
            apArticle.setLikes(0);
            // 保存
            save(apArticle);  // 返回ID

            //2 保存article_config 数据
            ApArticleConfig apArticleConfig = new ApArticleConfig();
            apArticleConfig.setIsForward(true);
            apArticleConfig.setIsComment(true);
            apArticleConfig.setIsDown(false);
            apArticleConfig.setIsDelete(false);
            // 文章id
            apArticleConfig.setArticleId(apArticle.getId());
            apArticleConfigMapper.insert(apArticleConfig);

            //3 保存文章article_content 数据
            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setContent(articleDto.getContent());
            // 文章ID
            apArticleContent.setArticleId(apArticle.getId());
            apArticleContentMapper.insert(apArticleContent);


        } else { // 修改

            // 查询文章
            ApArticle article = getById(articleDto.getId());
            if (article == null) {
                log.info("ApArticle getById is null: {}", articleDto.getId());

                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
            }

            // 修改 apArticle
            updateById(apArticle);

            // 修改 apArticleContent
            ApArticleContent articleContent = apArticleContentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery()
                    .eq(ApArticleContent::getArticleId, articleDto.getId()));
            if (articleContent == null) {
                log.info("articleContent getById is null: {}", articleDto.getId());
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            articleContent.setContent(articleDto.getContent());
            apArticleContentMapper.updateById(articleContent);

        }

        //4 返回结果  文章保存后的主键 ID
        return ResponseResult.okResult(apArticle.getId());
    }

    //======================================1/20
    @Value("${file.oss.web-site}")
    String webSite;


    /**
     * 根据参数加载文章列表
     *
     * @param loadtype 1为加载更多  2为加载最新
     * @param dto
     * @return
     */
    @Override
    public ResponseResult load(Short loadtype, ArticleHomeDto dto) {
        //1.判断 是否 为空
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2. 获取 传来 的 dto 中的 页码 判断 是否为空 不为空 则 设置默认值
        Integer size = dto.getSize();
        if (size == null || size <= 0) {
            size = 10;  //设置 默认 展示 值为 10
        }

        //size = Math.min(size, MAX_PAGE_SIZE)
        dto.setSize(size);

        // 设置 频道
        if (StringUtils.isBlank(dto.getTag())){
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }
        // 设置 最大 最小 时间
        if (dto.getMaxBehotTime()== null){
            dto.setMaxBehotTime(new Date());
        }

        if (dto.getMinBehotTime() ==null){
            dto.setMinBehotTime(new Date());
        }

        //判断类型
        if (!
                loadtype.equals(ArticleConstants.LOADTYPE_LOAD_MORE)
                &&
                loadtype.equals(ArticleConstants.LOADTYPE_LOAD_NEW))
        {
            //如果 类型 不等于 加载 更多 或者 加载 最新 那就 加载 更多
            loadtype =ArticleConstants.LOADTYPE_LOAD_MORE;
        }

        //3.执行 查询
        List<ApArticle> apArticleList
                = apArticleMapper.loadArticleList(dto, loadtype);

        //4.返回结果
        ResponseResult responseResult = ResponseResult.okResult(apArticleList);
        responseResult.setHost(webSite);


        return responseResult;
    }
//============================================1/21

    /**
     * 加载文章详情
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadArtilceInfo(ArticleInfoDto dto) {
        //1. 参数检查
        if (dto == null || dto.getArticleId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.获取 文章 id
        Long id = dto.getArticleId();
        //3.根据 id 查询 apArticleConfig
        ApArticleConfig apArticleConfig =
                apArticleConfigMapper
                        .selectOne(
                                Wrappers.<ApArticleConfig>lambdaQuery()
                                        .eq(ApArticleConfig::getArticleId, id));
        //3.1 判断 返回值 是否下架 是否删除
        if (apArticleConfig == null || apArticleConfig.getIsDown() || apArticleConfig.getIsDelete()){
          return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章已下架或者被删除！");
        }

        //4.查询文章内容
        ApArticleContent apArticleContent =
                apArticleContentMapper.selectOne(
                        Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, id));
       //4.1判断返回值
        if (apArticleContent == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章内容不存在！");
        }

        //封装 返回结果
        HashMap<String, Object> map = new HashMap<>();
        map.put("config",apArticleConfig);
        map.put("content",apArticleContent);

        return ResponseResult.okResult(map);
    }
}
